import { t } from 'i18next'
import React, { FC } from 'react'
import shallow from 'zustand/shallow'
import { ListItemGhost, RightWrap } from '../../components'
import { ListEmpty, ListTop, ListBody } from '@/components/List'
import { Droppable, Draggable, DragDropContextProvider } from '@/plugins/dnd'
import { FixedSizeList as List, ListChildComponentProps } from 'react-window'
import { ListItem } from './ListItem'
import { useData } from './hooks'
import { useChasingStore } from './store'
import { ChasingListModel } from './translator'
import { Button } from '@kedacom/react-next'
import AutoSizer from 'react-virtualized-auto-sizer'
import { revert_mt } from '@/api/manager/mt'

interface RowRendererProps extends ListChildComponentProps {
	data: ChasingListModel
}
const rowRenderer = React.memo(({ data: list, index, style }: RowRendererProps) => {
	const rowData = list[index]
	const dataTransfer = () => {
		return {
			data: {
				mt: revert_mt(rowData.mcc),
			},
			from: 'chasing',
		}
	}
	return (
		<Draggable
			style={style}
			index={index}
			dataTransfer={dataTransfer}
			ghostRender={<ListItemGhost data={rowData.mcc} />}
		>
			<ListItem {...rowData} />
		</Draggable>
	)
})
const Chasing: FC = () => {
	const { handleDrop, topActions, handleOrder, handleSave, handleBack } = useData()
	const { list } = useChasingStore(
		(state) => ({
			list: state.list,
		}),
		shallow
	)
	return (
		<>
			<RightWrap
				title={t('追呼设置')}
				action={<Button onClick={handleSave}>{t('确认设置')}</Button>}
				onBack={handleBack}
			>
				<ListTop title={t('追呼列表')} num={list.length} actions={topActions} />
				<ListBody order={handleOrder} isHideOrder={true}>
					<AutoSizer>
						{({ height }) => (
							<DragDropContextProvider>
								<Droppable onDrop={handleDrop}>
									{(setDroppableRef) =>
										list.length > 0 ? (
											<List
												width={280}
												height={height}
												itemCount={list.length}
												itemSize={32}
												itemData={list}
												outerRef={setDroppableRef}
												itemKey={(index, data) => data[index].mtKey}
											>
												{rowRenderer}
											</List>
										) : (
											<ListEmpty width={280} height={height} outerRef={setDroppableRef} />
										)
									}
								</Droppable>
							</DragDropContextProvider>
						)}
					</AutoSizer>
				</ListBody>
			</RightWrap>
		</>
	)
}
export default Chasing
